package com.zbl.zblproject.core.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Preconditions;
import com.zbl.zblproject.core.entity.*;
import com.zbl.zblproject.core.mapper.*;
import com.zbl.zblproject.core.service.OrderService;
import com.zbl.zblproject.core.utils.ResultUtil;
import com.zbl.zblproject.core.utils.StringUtil;
import com.zbl.zblproject.erp.entity.ErpGoods;
import com.zbl.zblproject.erp.entity.ErpInventoryOrder;
import com.zbl.zblproject.erp.entity.ErpOrder;
import com.zbl.zblproject.erp.entity.ErpTempOrderItem;
import com.zbl.zblproject.erp.mapper.ErpGoodMapper;
import com.zbl.zblproject.erp.mapper.ErpInventoryOrderMapper;
import com.zbl.zblproject.erp.mapper.ErpOrderMapper;
import com.zbl.zblproject.erp.mapper.ErpTempOrderItemMapper;
import com.zbl.zblproject.erp.service.ErpOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.ibatis.annotations.Param;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientException;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/10/11
 */
@Api(value = "用户订单接口", tags = {"用户订单接口"})
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private ErpOrderService erpOrderService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private ErpTempOrderItemMapper erpTempOrderItemMapper;

    @Autowired
    private ErpOrderMapper erpOrderMapper;

    @Autowired
    private SystemLoggerMapper systemLoggerMapper;

    @Autowired
    private ErpInventoryOrderMapper erpInventoryOrderMapper;

    @Autowired
    private ErpTempOrderItemMapper tempOrderItemMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private SmallUnitMapper smallUnitMapper;
    @Autowired
    private ErpGoodMapper erpGoodMapper;

    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @GetMapping("/logger-page/{current}/{size}")
    @ApiOperation("日志记录分页")
    public Result loggerPage(@ApiParam("页数") @PathVariable int current,
                             @ApiParam("数量") @PathVariable int size) {
        IPage<SystemLogger> loggerPage = new Page<>(current, size);
        loggerPage = systemLoggerMapper.selectPage(loggerPage, null);
        return ResultUtil.success("成功！", loggerPage);
    }

    @PostMapping("/logger")
    @ApiOperation("日志记录功能.")
    public Result logger(@ApiParam("名称") @RequestParam("name") String name,
                         @ApiParam("详细") @RequestParam("msg") String msg,
                         @ApiParam("路径") @RequestParam("url") String url) {
        SystemLogger logger = new SystemLogger();
        logger.setUserName(name);
        logger.setTime(LocalDateTime.now());
        logger.setMsg(msg);
        logger.setUrl(url);
        if (systemLoggerMapper.insert(logger) == 1) {
            return ResultUtil.success("记录成功!");
        }
        return ResultUtil.error("记录失败!");
    }


    @GetMapping("/invalid-order/{orderSn}")
    @ApiOperation("订单作废")
    public Result invalid(@ApiParam("订单号") @PathVariable String orderSn) {
        if (orderService.invalidOrder(orderSn)) {
            return ResultUtil.success("订单操作成功!");
        }
        return ResultUtil.error("订单操作失败!");
    }

    @GetMapping("/remote-origin/{orderSn}")
    @ApiOperation("获取远程订单号")
    public Result remoteGetOriginOrder(@ApiParam("订单号") @PathVariable("orderSn") String orderSn) {
        String originOrderSn = erpOrderMapper.selectOriginOrderSnByOrderSn(orderSn);
        if (originOrderSn != null) {
            return ResultUtil.success("成功", originOrderSn);
        } else {
            return ResultUtil.error("失败!");
        }
    }

    @PostMapping("/remote-submit")
    @ApiOperation("远程订单提交接口")
    public Result remoteSubmit(@ApiParam("JSON信息") @RequestParam("json") String json,
                               @ApiParam("用户名称") @RequestParam("userName") String userName) {
        try {
            List<Order> orders = JSONArray.parseArray(json, Order.class);
            AdminUser user = adminUserMapper.selectOneByName(userName);
            if (user == null) {
                throw new RuntimeException("用户不存在!");
            }
            orderService.submitOrder(orders, user);
            return ResultUtil.success("成功!");
        } catch (RuntimeException e) {
            return ResultUtil.error(e.getMessage());
        }
    }

    @GetMapping("/warehouse-delivery/{orderSn}")
    @ApiOperation("通知仓库发货")
    public Result warehouseDelivery(@ApiParam("订单号") @PathVariable String orderSn) {
        if (orderService.warehouseDelivery(orderSn)) {
            return ResultUtil.success("通知成功!");
        }
        return ResultUtil.error("通知失败!");
    }

    @GetMapping("/order-list/{orderSn}")
    @ApiOperation("获取门店订单项")
    public Result orderList(@ApiParam("订单号") @PathVariable String orderSn) {
        List<ErpTempOrderItem> items = erpTempOrderItemMapper.listByOrderSn(Arrays.asList(orderSn));
        if (items.size() > 0) {
            for (ErpTempOrderItem item : items) {
                item.setDiscount(BigDecimal.ONE);
                ErpGoods goods = erpGoodMapper.selectById(item.getGoodsId());
                Supplier supplier = supplierMapper.selectById(goods.getSuppliersId());
                item.setLogisticsCostRatio(supplier.getLogisticsCostRatio());
            }
        } else {
            ErpInventoryOrder orders = erpInventoryOrderMapper.selectByInSn(orderSn);
            if (orders == null) {
                throw new RuntimeException("没有发现订单!");
            }
            items = tempOrderItemMapper.listByOrderItemNotDescs(orders.getId());
            items.forEach(x -> {
                ErpGoods goods = erpGoodMapper.selectById(x.getGoodsId());
                x.setBrandName(brandMapper.selectById(goods.getBrandId()).getBrandName());
                x.setSupplier(supplierMapper.selectById(goods.getSuppliersId()));
                SmallUnit unit = smallUnitMapper.selectById(goods.getSmallunitId());
                if (unit != null) {
                    x.setGoodsUnit(unit.getName());
                } else {
                    x.setGoodsUnit("件");
                }
                x.setGoodsSn(goods.getGoodsSn());
                x.setStock(goods.getGoodsNumber());
                x.setNumberUnit(String.valueOf(goods.getNumberUnit()));
                x.setIsTh(1);
            });
        }
        return ResultUtil.success("成功", items);
    }

    @PostMapping("/updateContext/{orderSn}")
    @ApiOperation("更新订单备注")
    public Result updateOrderContext(@ApiParam("订单号") @PathVariable String orderSn,
                                     @ApiParam("备注") @RequestParam("context") String context) {
        try {
            if (orderService.updateOrderContext(orderSn, context)) {
                return ResultUtil.success("更新成功!");
            } else {
                return ResultUtil.error("更新失败!");
            }
        } catch (RuntimeException e) {
            return ResultUtil.error(e.getMessage());
        }
    }

    @PostMapping("/updateConfirm/{orderSn}")
    @ApiOperation("更新订单确认信息")
    public Result updateOrderComfirm(@ApiParam("订单号") @PathVariable String orderSn,
                                     @ApiParam("状态") @RequestParam("status") int status,
                                     @ApiParam("操作人ID") @RequestParam("userId") int userId) {
        try {
            if (orderService.updateOrderConfirm(orderSn, status, userId)) {
                return ResultUtil.success("更新成功!");
            } else {
                return ResultUtil.error("更新失败!");
            }
        } catch (RuntimeException e) {
            return ResultUtil.error(e.getMessage());
        }
    }

    @GetMapping("/ended-order/{orderSn}")
    @ApiOperation("订单终结")
    public Result endedOrder(@ApiParam("订单号") @PathVariable String orderSn,
                             @ApiParam("用户ID") @RequestParam("userId") int userId) {
        AdminUser user = getUserById(userId);
        if (orderService.orderEnded(orderSn)) {
            erpOrderService.endedOwe(orderSn, user);
            return ResultUtil.success("订单终结成功!");
        }
        return ResultUtil.error("订单终结失败!");
    }


    @GetMapping("/factory-order-sn")
    @ApiOperation("获取工厂订单")
    public Result factoryOrderSn(@ApiParam("模式 0:CGDD ") @RequestParam("mode") int mode,
                                 @ApiParam("厂家名称") @RequestParam("name") String name,
                                 @ApiParam("开始时间") @RequestParam("start") String start,
                                 @ApiParam("结束时间") @RequestParam("end") String end,
                                 @ApiParam("订单号") @RequestParam("orderSn") String orderSn,
                                 @ApiParam("订单号") @RequestParam("factoryMake") String factoryMake) {

        List<FactoryOrder> list = orderService.getSupplierOrderListForOrderSn(mode, start, end, name, orderSn, factoryMake);
        if (list == null) {
            return ResultUtil.error("没有数据");
        }
        return ResultUtil.success("成功", list);
    }


    @GetMapping("/factory-order-sn/{current}/{size}/{isInto}")
    @ApiOperation("获取工厂订单")
    public Result factoryOrderSnByLimit(@ApiParam("模式 0:CGDD ") @RequestParam("mode") int mode,
                                        @ApiParam("厂家名称") @RequestParam("name") String name,
                                        @ApiParam("开始时间") @RequestParam("start") String start,
                                        @ApiParam("结束时间") @RequestParam("end") String end,
                                        @ApiParam("订单号") @RequestParam("orderSn") String orderSn,
                                        @ApiParam("分页") @PathVariable Integer current,
                                        @ApiParam("数量") @PathVariable Integer size,
                                        @ApiParam("是否入库") @PathVariable int isInto) {
        if (current <= 0 || size <= 0) {
            return ResultUtil.error("参数错误");
        }
        return orderService.getSupplierOrderListForOrderSnByLimit(mode, start, end, name, orderSn, current, size, isInto);
    }


    @GetMapping("/order-status/{orderSn}/{index}")
    @ApiOperation("获取订单的当前状态")
    public String orderStatus(@ApiParam("订单号") @PathVariable String orderSn,
                              @ApiParam("下标") @PathVariable int index) {
        return index + "," + orderService.orderStatus(orderSn);
    }


    @GetMapping("/factory-order")
    @ApiOperation("获取工厂订单")
    public Result factoryOrder(@ApiParam("模式 0:CGDD 1:非CGDD 2:合并门店订单 ") @RequestParam("mode") int mode,
                               @ApiParam("厂家名称") @RequestParam("name") String name,
                               @ApiParam("开始时间") @RequestParam("start") String start,
                               @ApiParam("结束时间") @RequestParam("end") String end,
                               @ApiParam("订单号") @RequestParam("orderSn") String orderSn) {
        List<FactoryOrder> list = orderService.getSupplierOrder(mode, start, end, name, orderSn);
        if (list == null) {
            return ResultUtil.error("没有数据");
        }
        return ResultUtil.success("成功", list);
    }


    @GetMapping("/factory-order/{factoryName}")
    @ApiOperation("获取工厂订单")
    public Result factoryOrder(@ApiParam("工厂名称") @PathVariable String factoryName) {
        FactoryOrder factoryOrder = orderService.getSupplierOrderByName(factoryName, "", "");
        if (factoryOrder != null) {
            return ResultUtil.success("成功", factoryOrder);
        } else {
            return ResultUtil.error("失败");
        }
    }

    @GetMapping("/order-sn/{factoryName}/{orderSn}")
    @ApiOperation("获取工厂订单")
    public Result orderSn(@ApiParam("工厂名称") @PathVariable String factoryName, @ApiParam("订单号") @PathVariable String orderSn) {
        FactoryOrder factoryOrder = orderService.getSupplierOrderByName(factoryName, orderSn);
        if (factoryOrder != null) {
            return ResultUtil.success("成功", factoryOrder);
        } else {
            return ResultUtil.error("失败");
        }
    }


    @GetMapping("/storelist")
    @ApiOperation("获取门店数据,门店订单引入")
    public Result storeList() {
        return ResultUtil.success("成功!", erpOrderService.getUserOrdersByNotDeliver(0));
    }

    @GetMapping("/confirm-storelist")
    @ApiOperation("获取门店数据,门店订单引入")
    public Result confirmStoreList() {
        return ResultUtil.success("成功!", erpOrderService.getUserOrdersByIsConfirm(0));
    }

    @GetMapping("/confirm-desc")
    @ApiOperation("门店订单分类列表")
    public Result confirmDesc() {
        List<Order> orders = erpOrderService.getUserOrdersDesc();
        if (orders.isEmpty()) {
            return ResultUtil.error("没有订单数据");
        }
        return ResultUtil.success("成功!", orders);
    }

    @GetMapping("/get-confirm-order/{orderSn}")
    @ApiOperation("门店订单对应商品列表")
    public Result getConfirmOrder(@ApiParam("订单号") @PathVariable String orderSn) {
        List<ErpTempOrderItem> list = erpOrderService.getTempOrderByOrderSnAndNotOut(orderSn);
        if (list.isEmpty()) {
            return ResultUtil.error("没有订单数据");
        }
        return ResultUtil.success("成功", list);
    }

    @GetMapping("/erplist/{pageCur}/{pageSize}")
    @ApiOperation("获取用户可执行ERP订单数据")
    public Result orderList(@Param("当前页") @PathVariable int pageCur, @Param("显示条数") @PathVariable int pageSize) {
        return ResultUtil.success("成功!", erpOrderService.getOrdersByNotDeliver(pageCur, pageSize, 0, 0));
    }

    @GetMapping("/owelist/{mode}")
    @ApiOperation("欠缺货订单列表")
    public Result oweList(@ApiParam("欠缺货模式,0:欠货  1:缺货") @PathVariable int mode,
                          @Param("orderSn") String orderSn, @Param("start") String start, @Param("end") String end) {
        return ResultUtil.success("成功", erpOrderService.getOweTtemListByMode(mode,orderSn,start,end));
    }

    @GetMapping("/endedlist")
    @ApiOperation("终结订单详情")
    public Result endedList() {
        return ResultUtil.success("成功!", erpOrderService.getItemListForEnded());
    }

    @GetMapping("/invoice/{name}")
    @ApiOperation("获取门店的配货单")
    public Result invoice(@ApiParam("门店名称") @PathVariable String name) {
        QueryWrapper<AdminUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", name);
        AdminUser user = adminUserMapper.selectOne(wrapper);
        if (user == null || user.getStatus() != 0) {
            return ResultUtil.error("用户不存在或被封禁!");
        }
        return ResultUtil.success("成功", orderService.getInvoiceOrderById(user.getUserId()));
    }

    @GetMapping("/new-invoice/{name}")
    @ApiOperation("获取门店的配货单")
    public Result newInvoice(@ApiParam("门店名称") @PathVariable String name) {
        QueryWrapper<AdminUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", name);
        AdminUser user = adminUserMapper.selectOne(wrapper);
        if (user == null || user.getStatus() != 0) {
            return ResultUtil.error("用户不存在或被封禁!");
        }
        return ResultUtil.success("成功", orderService.getInvoiceOrderByIdforWh(user.getUserId()));
    }

    @PostMapping("/add-purchase/{orderNo}")
    @ApiOperation("添加采购单")
    public Result addPurchase(@ApiParam("订单号") @PathVariable String orderNo,
                              @ApiParam("订单商品") @RequestParam("items") String items,
                              @ApiParam("用户ID") @RequestParam("userId") Integer userId,
                              @ApiParam("地址ID") @RequestParam("addressId") Integer addressId,
                              @ApiParam("选中的orderSn") @RequestParam("arrays") String[] arrays,
                              @ApiParam("操作ID") @RequestParam("operatorId") Integer operatorId) {
        try {

            List<ErpTempOrderItem> list = json2item(items);

            if (list.isEmpty()) {
                throw new RuntimeException("提交的商品数量为空!");
            }

            Order order = orderService.createOrder(orderNo, operatorId, userId, addressId, 1, 1, 1, 1, list, "");

            orderService.updateOrderOp(order, arrays);

            return ResultUtil.success("成功!", order);

        } catch (RuntimeException e) {

            return ResultUtil.error(e.getMessage());

        }
    }

    @PostMapping("/add-store/{mode}/{orderNo}")
    @ApiOperation("添加门店单")
    public Result addStore(@ApiParam("订单号") @PathVariable String orderNo,
                           @ApiParam("订单商品") @RequestParam("items") String items,
                           @ApiParam("用户ID") @RequestParam("userId") Integer userId,
                           @ApiParam("操作者ID") @RequestParam("operator") Integer operatorId,
                           @ApiParam("地址ID") @RequestParam("addressId") Integer addressId,
                           @ApiParam("模式") @PathVariable("mode") Integer mode) {
        try {
            logger.info("订单号: {}", orderNo);
            logger.info("用户ID: {}", userId);
            logger.info("操作者ID: {}", operatorId);
            logger.info("地址ID: {}", addressId);
            logger.info("模式: {}", mode);
            List<ErpTempOrderItem> list = json2item(items);
            if (list.isEmpty()) {
                throw new RuntimeException("提交的商品数量为空!");
            }
            Order order = null;
            if (mode == 1) {
                //按供应商将list分组
                Map<String, List<ErpTempOrderItem>> skuIdMap = new HashMap<>();
                for (ErpTempOrderItem skuVo : list) {
                    List<ErpTempOrderItem> tempList = skuIdMap.get(skuVo.getSupplierName());
                    /*如果取不到数据,那么直接new一个空的ArrayList**/
                    if (tempList == null) {
                        tempList = new ArrayList<>();
                        tempList.add(skuVo);
                        skuIdMap.put(skuVo.getSupplierName(), tempList);
                    } else {
                        /*某个sku之前已经存放过了,则直接追加数据到原来的List里**/
                        tempList.add(skuVo);
                    }
                }
                List<Order> orders = new ArrayList<>();
                for (String s : skuIdMap.keySet()) {
                    Date date = new Date();
                    SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
                    String tp = sd.format(date) + (int) ((Math.random() * 9 + 1) * 100000000);//生成17位随机数 规则:前8位为年月日的拼接后9位为随机数
                    order = orderService.createOrder(tp, operatorId, userId, addressId, 1, 0, 0, 0, skuIdMap.get(s), "");
                    orders.add(order);
                }
                return ResultUtil.success("成功!", orders);
            } else if (mode == 0) {
                //保存订单
                order = orderService.updateOrder(orderNo, operatorId, userId, addressId, 1, 0, 0, 0, list);
            }
            if (order != null) {
                return ResultUtil.success("成功!", order);
            } else {
                return ResultUtil.error("异常的模式");
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResultUtil.error(e.getMessage());
        }
    }

    @GetMapping("/copyOrder/{orderSn}")
    @ApiOperation("复制用户订单下面的商品")
    public Result copyOrder(@ApiParam("订单号") @PathVariable String orderSn) {
        List<ErpGoods> list = orderService.getGoodsByOrderSn(orderSn);
        if (list.isEmpty()) {
            return ResultUtil.error("订单项目为空!");
        }
        return ResultUtil.success("成功!", list);
    }

    @GetMapping("/updateStatus/{status}")
    @ApiOperation("修改订单终结状态已经作废状态")
    @ResponseBody
    public Result updateStatus(@Param("状态码") @PathVariable int status,
                               @Param("订单编号") @RequestParam("orderSn") String orderSn) {
        int i = orderMapper.updateStatus(orderSn, status);
        if (i > 0) {
            return ResultUtil.success("成功");
        } else {
            return ResultUtil.success("失败");
        }
    }

    @GetMapping("/goback/{orderSn}")
    @ApiOperation("该订单的关联订单回滚.")
    public Result goBackOrder(@ApiParam("订单号") @PathVariable String orderSn) {
        return ResultUtil.error("接口未开放!");
    }

    private List<ErpTempOrderItem> json2item(String json) {
        logger.info("json信息: {}", json);
        JSONArray array = JSONArray.parseArray(json);
        List<ErpTempOrderItem> list = new ArrayList<>(array.size());
        JSONObject jsonObject = null;
        ErpTempOrderItem orderItem = null;
        for (int i = 0; i < array.size(); i++) {
            jsonObject = array.getJSONObject(i);
            orderItem = new ErpTempOrderItem();
            System.out.println(i);
            if (jsonObject.containsKey("goodsId")) {
                orderItem.setGoodsName(jsonObject.getString("goodsName"));
                orderItem.setGoodsId(jsonObject.getInteger("goodsId"));
                orderItem.setGoodsNum(jsonObject.getInteger("goodsNum"));
                orderItem.setGoodsUnit(jsonObject.getString("goodsUnit"));
                orderItem.setGoodsDesc(jsonObject.getString("goodsDesc"));
                orderItem.setSpecifications(jsonObject.getString("specifications"));
                orderItem.setBrandName(jsonObject.getString("brandName"));
                orderItem.setOrderItemId(jsonObject.getInteger("orderItemId"));
                orderItem.setDiscount(jsonObject.getBigDecimal("discount"));
                orderItem.setSupplierName(jsonObject.getString("suppliersName"));
                list.add(orderItem);
            } else {
                continue;
            }

        }
        return list;
    }

    private AdminUser getUserById(int id) {
        AdminUser user = adminUserMapper.selectById(id);
        Preconditions.checkNotNull(user, "未发现对应的用户");
        if (user.getStatus() != 0) {
            throw new RuntimeException("用户未被启用");
        }
        return user;
    }

    @PostMapping("/new-submit-goods")
    @ApiOperation("在购物车中提交订单")
    public Result submitGoodsNew(@ApiParam("购物车ID") @RequestParam("array") String array,
                                 @ApiParam("用户ID") @RequestParam("userId") int userId) {
        try {
            AdminUser user = adminUserMapper.selectUserById(userId);
            if (user == null) {
                return ResultUtil.error("没有发现这个用户");
            }
            List<CartItem> cartItems = JSONArray.parseArray(array, CartItem.class);
            //logger.info("json:{}", array);
            orderService.submitOrderNew(cartItems, user);
            return ResultUtil.success("订单生成成功!");
        } catch (RestClientException e) {
            e.printStackTrace();
            return ResultUtil.error("远程服务器连接失败!");
        } catch (RuntimeException e) {
            return ResultUtil.error(e.getMessage());
        }
    }

    @GetMapping("/mdOrders")
    @ApiOperation("根据供应商查询未确认的门店订单")
    public Result mdOrders(@ApiParam("开始时间") @RequestParam("start") long start,
                           @ApiParam("结束时间") @RequestParam("end") long end,
                           @ApiParam("结束时间") @RequestParam("supId") int supId) {
        start = start / 1000;
        end = end / 1000;
        JSONArray jsonArray = orderService.mdOrders(start, end, supId);
        return ResultUtil.success("成功", jsonArray);
    }

    @GetMapping("/getSup")
    @ApiOperation("查询未确认的门店订单的供应商")
    public Result getSup(@ApiParam("开始时间") @RequestParam("start") long start,
                         @ApiParam("结束时间") @RequestParam("end") long end) {
        start = start / 1000;
        end = end / 1000;
        List<Supplier> suppliers = orderService.getSup(start, end);
        if (suppliers.size() > 0) {
            return ResultUtil.success("成功", suppliers);
        } else {
            return ResultUtil.error("没有查询到未确认的门店订单");
        }
    }

    @PostMapping("/getOrderItem")
    @ApiOperation("查询未确认的门店订单的供应商")
    public Result getOrderItem(@RequestParam("ids") String ids) {
        List<OrderItem> orderItems = orderItemMapper.getGoodsName(ids);
//        JSONArray array = new JSONArray();
        for (OrderItem orderItem : orderItems) {
//            JSONObject object = new JSONObject();
//            Order order = orderMapper.selectByOrderSn(orderItem.getOrderSn());
//            object.put("orderSn", order.getOrderSn());
//            AdminUser adminUser = adminUserMapper.selectById(order.getUserId());
//            object.put("userName", adminUser.getUserName());
//            object.put("createTime", order.getCreateTime() * 1000);
//            object.put("orderItem", orderItem);
//            array.add(object);
            if (orderItem.getSuppliersId() != 0) {
                Supplier supplier = supplierMapper.selectById(orderItem.getSuppliersId());
                orderItem.setSupplierName(supplier.getSuppliersName());
            }
            ErpGoods goods = erpGoodMapper.selectById(orderItem.getGoodsId());
            if (goods == null) {
                return ResultUtil.error(orderItem.getGoodsName() + "不存在!");
            }
            orderItem.setGoodsNumber(goods.getGoodsNumber());
            String numberUnit="";
            if (!StringUtil.isNullOrEmpty(goods.getSpecifications())){
                numberUnit = String.valueOf(orderItem.getGoodsNum()/goods.getNumberUnit());
            }
            orderItem.setNumberUnit(numberUnit);
        }
        return ResultUtil.success("成功", orderItems);
    }

    @GetMapping("/checkOrderSn")
    public Result checkOrderSn(@RequestParam("orderSn") String orderSn) {
        QueryWrapper<ErpOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("origin_order_sn", orderSn);
        ErpOrder erpOrder = erpOrderMapper.selectOne(queryWrapper);
        if (erpOrder != null) {
            return ResultUtil.error("该单号已被引入，单号为:" + erpOrder.getOrderInfo());
        }

        return ResultUtil.success("成功");
    }

    @GetMapping("/dd")
    public Result dd() {
        List<String> orders = orderItemMapper.getString();
        for (String s : orders) {
            System.out.println(s);
        }
        return ResultUtil.success("");
    }

//    public static void main(String[] args) {
//        Date date = new Date();
//        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
//        String tp = sd.format(date);
//        System.out.println(tp + (int) ((Math.random() * 9 + 1) * 100000000));
//        List<ErpTempOrderItem> list = json2items("[{\"goodsId\":11450,\"goodsDesc\":\"1件*60个\",\"brandName\":\"庆展\",\"goodsName\":\"QZ-PQ16-1WL不锈钢圆形饭盒16cm\",\"suppliersName\":\"揭阳庆展五金\",\"goodsNum\":1,\"allNum\":0,\"shopPrice\":17.53,\"goodsUnit\":\"个\",\"specifications\":\"1件*60个\",\"P_address\":\"广东揭阳\",\"orderItemId\":0,\"discount\":1,\"numberUnit\":60},{\"goodsId\":11220,\"goodsDesc\":\"1件*40台\",\"brandName\":\"赛阁\",\"goodsName\":\"*SG-B03灭蚊灯\",\"suppliersName\":\"揭阳赛阁电器\",\"goodsNum\":1,\"allNum\":78,\"shopPrice\":32,\"goodsUnit\":\"台\",\"specifications\":\"1件*40台\",\"P_address\":\"广东揭阳\",\"orderItemId\":0,\"discount\":1,\"numberUnit\":40},{\"goodsId\":11219,\"goodsDesc\":\"1件*40台\",\"brandName\":\"赛阁\",\"goodsName\":\"*SG-B02灭蚊灯\",\"suppliersName\":\"揭阳赛阁电器\",\"goodsNum\":1,\"allNum\":2,\"shopPrice\":33,\"goodsUnit\":\"台\",\"specifications\":\"1件*40台\",\"P_address\":\"广东揭阳\",\"orderItemId\":0,\"discount\":1,\"numberUnit\":40},{\"goodsId\":11135,\"goodsDesc\":\"1件*18桶\",\"brandName\":\"彩虹\",\"goodsName\":\"*CH-5624蚊香特惠桶装\",\"suppliersName\":\"成都彩虹电器\",\"goodsNum\":1,\"allNum\":162,\"shopPrice\":7.6,\"goodsUnit\":\"\",\"specifications\":\"1件*18桶\",\"P_address\":\"四川成都\",\"orderItemId\":0,\"discount\":1,\"numberUnit\":18},{\"goodsId\":11128,\"goodsDesc\":\"1件*24瓶\",\"brandName\":\"彩虹\",\"goodsName\":\"*CH-5250杀虫气雾剂500ml柠檬\",\"suppliersName\":\"成都彩虹电器\",\"goodsNum\":1,\"allNum\":240,\"shopPrice\":11.12,\"goodsUnit\":\"瓶\",\"specifications\":\"1件*24瓶\",\"P_address\":\"四川成都\",\"orderItemId\":0,\"discount\":1,\"numberUnit\":24},{\"goodsId\":11119,\"goodsDesc\":\"1件*20套\",\"brandName\":\"彩虹\",\"goodsName\":\"*CH-5113J电热蚊香液特惠双瓶装乖乖\",\"suppliersName\":\"成都彩虹电器\",\"goodsNum\":1,\"allNum\":199,\"shopPrice\":18.25,\"goodsUnit\":\"\",\"specifications\":\"1件*20套\",\"P_address\":\"四川成都\",\"orderItemId\":0,\"discount\":1,\"numberUnit\":20},{\"goodsId\":11122,\"goodsDesc\":\"1件*40套\",\"brandName\":\"彩虹\",\"goodsName\":\"*CH-5155蚊香液直插器超值装1+1无味36ml\",\"suppliersName\":\"成都彩虹电器\",\"goodsNum\":1,\"allNum\":359,\"shopPrice\":12.48,\"goodsUnit\":\"套\",\"specifications\":\"1件*40套\",\"P_address\":\"四川成都\",\"orderItemId\":0,\"discount\":1,\"numberUnit\":40}]");        /*2、分组算法**/
//        Map<String, List<ErpTempOrderItem>> skuIdMap = new HashMap<>();
//        for (ErpTempOrderItem skuVo : list) {
//            List<ErpTempOrderItem> tempList = skuIdMap.get(skuVo.getSupplierName());
//            /*如果取不到数据,那么直接new一个空的ArrayList**/
//            if (tempList == null) {
//                tempList = new ArrayList<>();
//                tempList.add(skuVo);
//                skuIdMap.put(skuVo.getSupplierName(), tempList);
//            } else {
//                /*某个sku之前已经存放过了,则直接追加数据到原来的List里**/
//                tempList.add(skuVo);
//            }
//        }
//
//        /*3、遍历map,验证结果**/
//        for (String skuId : skuIdMap.keySet()) {
//            System.out.println(skuIdMap.get(skuId));
//        }
//
//    }
//
//    public static List<ErpTempOrderItem> json2items(String json) {
////        logger.info("json信息: {}", json);
//        JSONArray array = JSONArray.parseArray(json);
//        List<ErpTempOrderItem> list = new ArrayList<>(array.size());
//        JSONObject jsonObject = null;
//        ErpTempOrderItem orderItem = null;
//        for (int i = 0; i < array.size(); i++) {
//            jsonObject = array.getJSONObject(i);
//            orderItem = new ErpTempOrderItem();
////            System.out.println(i);
//            orderItem.setGoodsName(jsonObject.getString("goodsName"));
//            orderItem.setGoodsId(jsonObject.getInteger("goodsId"));
//            orderItem.setGoodsNum(jsonObject.getInteger("goodsNum"));
//            orderItem.setGoodsUnit(jsonObject.getString("goodsUnit"));
//            orderItem.setGoodsDesc(jsonObject.getString("goodsDesc"));
//            orderItem.setSpecifications(jsonObject.getString("specifications"));
//            orderItem.setBrandName(jsonObject.getString("brandName"));
//            orderItem.setOrderItemId(jsonObject.getInteger("orderItemId"));
//            orderItem.setDiscount(jsonObject.getBigDecimal("discount"));
//            orderItem.setSupplierName(jsonObject.getString("suppliersName"));
//            list.add(orderItem);
//        }
//        return list;
//    }

}